package com.lanou3g.view;

import com.lanou3g.controller.LoginController;
import com.lanou3g.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

//url后加.action是为了和jsp或者其他静态页面做区分
//一看见这个路径,就知道它访问的是个servlet
//servlet三件事      获取前段传来的参数
       //         调用 controller方法
@WebServlet(name = "LoginServlet",urlPatterns = "/login.action")
public class LoginServlet extends HttpServlet {

    private LoginController loginController
            =new LoginController();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             //获取前端参数
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String username =request.getParameter("username");
        String password =request.getParameter("password");
        String mode =request.getParameter("mode");

        User user=loginController.login(username,password);
        if (user==null){
            //登录失败
            String msg="用户名/密码错误,点击返回登录页面";
            String path ="/login.jsp";
            request.setAttribute("msg",msg);
            request.setAttribute("path",path);
            response.setStatus(302);
            response.setHeader("Refresh","5;URL=/l0gin.jsp");
            request.getRequestDispatcher("/msg.jsp").forward(request,response);
        }else {
            //登录成功
            HttpSession session=request.getSession();
            session.setAttribute("user",user);
            if ("week.".equals(mode)){
                //7天免登录
                session.setMaxInactiveInterval(7*24*60*60);
                Cookie cookie =new Cookie("JSESSIONID",session.getId());
                cookie.setPath("/");
                cookie.setMaxAge(7*24*60*60);
                response.addCookie(cookie);
            }
            response.sendRedirect("/index.jsp");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     this.doPost(request,response);
    }
}
